package com.sunyard.manage.service.impl;

import com.sunyard.dal.bo.device.key.KeyWarningQueryBO;
import com.sunyard.dal.bo.device.lock.LockWarningQueryBO;
import com.sunyard.dal.bo.dashboard.MapDataBO;
import com.sunyard.dal.bo.warning.NotWorkingTimeInitBo;
import com.sunyard.dal.bo.warning.WarningInfoQueryBO;
import com.sunyard.dal.dto.HomepageDisplayDTO;
import com.sunyard.dal.dto.MapDataDTO;
import com.sunyard.dal.dto.RegionTerminalDTO;
import com.sunyard.dal.dto.SignNumberResDTO;
import com.sunyard.dal.dto.TaskTimeDTO;
import com.sunyard.dal.dto.TaskTypeDTO;
import com.sunyard.dal.dto.TerminaAuditCountDTO;
import com.sunyard.dal.dto.TerminalWarningQueryDTO;
import com.sunyard.dal.dto.WarningInfoDTO;
import com.sunyard.dal.mapper.CityMapper;
import com.sunyard.dal.mapper.FingerCopyMapper;
import com.sunyard.dal.mapper.OperateHistoryMapper;
import com.sunyard.dal.mapper.OperatorCopyMapper;
import com.sunyard.dal.mapper.OperatorMapper;
import com.sunyard.dal.mapper.OrganizationMapper;
import com.sunyard.dal.mapper.PopedomMapper;
import com.sunyard.dal.mapper.TaskMapper;
import com.sunyard.dal.mapper.TerminalCopyMapper;
import com.sunyard.dal.mapper.TerminalMapper;
import com.sunyard.manage.service.HomepageDisplayService;
import com.sunyard.manage.service.OperatorService;
import com.sunyard.redisUtil.RedisUtils;
import com.sunyard.utils.DateUtil;
import com.sunyard.utils.Response.BaseResult;
import com.sunyard.utils.Response.GetResult;
import com.sunyard.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.sunyard.utils.DateUtil.getQueryType;
import static com.sunyard.utils.DateUtil.getStringTime;

@Service
public class HomepageDisplayServiceImpl implements HomepageDisplayService {

    @Autowired
    OperatorMapper operatorMapper;
    @Autowired
    OperatorCopyMapper operatorCopyMapper;
    @Autowired
    TaskMapper taskMapper;
    @Autowired
    TerminalCopyMapper terminalCopyMapper;
    @Autowired
    TerminalMapper terminalMapper;
    @Autowired
    OperateHistoryMapper operateHistoryMapper;
    @Autowired
    OrganizationMapper organizationMapper;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private FingerCopyMapper fingerCopyMapper;
    @Autowired
    private CityMapper cityMapper;
    @Autowired
    private PopedomMapper popedomMapper;
    @Autowired
    private OperatorService operatorService;

    @Value("${WarningInfo.timeOut}")
    private long timeOut;

    @Override
    public BaseResult getCount(HttpServletRequest request) {
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        HomepageDisplayDTO homepageDisplayDTO = new HomepageDisplayDTO();
        //获取当前机构及下属机构id集合
        List<String> orgIds = getListOrgIds(orgId);
        orgIds.add(orgId);

        //未关闭锁的数量（当日）
        LockWarningQueryBO warningQueryBO = new LockWarningQueryBO();
        warningQueryBO.setOrgIdList(orgIds);
        //根据当前时间 查询网点需要的数据
        long queryTime = DateUtil.getQueryTime();
        warningQueryBO.setEnd(queryTime);
        List<TerminalWarningQueryDTO> warningList = terminalMapper.queryLockWarningNew(warningQueryBO);
        int notLockedCount = warningList.size();

        //未上传日志钥匙数量（当日）
        KeyWarningQueryBO keyWarningQueryBO = new KeyWarningQueryBO();
        keyWarningQueryBO.setOrgIdList(orgIds);
        //long timeOut = 15 * 24 * 60 * 60 * 1000L;
        keyWarningQueryBO.setTimeOut(timeOut);
        keyWarningQueryBO.setCurrentTime(DateUtil.getEndOfTodDay().getTime());
        keyWarningQueryBO.setEnd(queryTime);
        List<TerminalWarningQueryDTO> keyWarningList = terminalMapper.queryKeyWarningNew(keyWarningQueryBO);
        int notSignInCount = keyWarningList.size();

        //未上传日志机构
        List<String> orgIdList = terminalMapper.getKeyOrgidList();
        List<String> orgKeyList = new ArrayList<>();
        for (String id : orgIds) {
            for (String ids : orgIdList) {
                if (id.equals(ids)) {
                    orgKeyList.add(ids);
                }
            }
        }
        WarningInfoQueryBO warningInfoQueryBO = new WarningInfoQueryBO();
        List<WarningInfoDTO> warningInfoList = new ArrayList<>();
        if (orgKeyList.size() > 0) {
            warningInfoQueryBO.setOrgIdList(orgKeyList);
            warningInfoQueryBO.setTimeOut(timeOut);
            warningInfoQueryBO.setCurrentTime(System.currentTimeMillis());
            warningInfoQueryBO.setEnd(queryTime);
            warningInfoList = organizationMapper.queryWarningInfo(warningInfoQueryBO);
        }
        int notUploadLogCount = warningInfoList.size();

        //开关锁操作数量（当日）
       /* int lockOperatorCountBySameDay = operateHistoryMapper.getLockOperatorCountBySameDay(orgIds);
        //开关锁操作数量（当月）
        int lockOperatorCountBySameMonth = operateHistoryMapper.getLockOperatorCountBySameMonth(orgIds);
        //尾箱操作数量（当日）
        int tailBoxOperatorCountBySameDay = operateHistoryMapper.getTailBoxOperatorCountBySameDay(orgIds);
        //尾箱操作数量（当月）
        int tailBoxOperatorCountBySameMonth = operateHistoryMapper.getTailBoxOperatorCountBySameMonth(orgIds);*/
        //待审核人员数量
        int operatorAuditCount = operatorCopyMapper.getOperatorAuditCount(orgIds);
        //待审核指纹数量
        int fingerAuditCount = fingerCopyMapper.getFingerAuditCount(orgIds);
        //待审核任务数量
        int taskAuditCount = taskMapper.getTaskAuditCount(orgIds);
        //待审核设备数量
        int terminaAuditCount = terminalCopyMapper.getTerminalCount(orgIds);
        //待审核锁具数量
        int lockAuditCount = terminalCopyMapper.getLockAuditCount(orgIds);
        //待审核尾箱数量
        int tailBoxCount = terminalCopyMapper.getTailBoxCount(orgIds);
        //待审核钥匙数量
        int keyAuditCount = terminalCopyMapper.getKeyAuditCount(orgIds);
        //待审核PDA数量
        int pdaAuditCount = terminalCopyMapper.getPdaAuditCount(orgIds);
        //待审核RFID数量
        int rfidAuditCount = terminalCopyMapper.getRfidAuditCount(orgIds);
        //非工作日志时间查询
        String stringTime = getStringTime();
        NotWorkingTimeInitBo notWorkingTimeInitBo = new NotWorkingTimeInitBo();
        notWorkingTimeInitBo.setEndTime(stringTime);
        notWorkingTimeInitBo.setOrgIds(orgIds);
        Integer queryType = getQueryType();
        int notWorkingTimeLogCount = -1;
        if (2 == queryType) {
            Boolean bool = redisUtils.keyIsExists("operatorHistory:" + orgId);
            if (bool) {
                notWorkingTimeLogCount = redisUtils.get("operatorHistory:" + orgId, Integer.class);
            } else {
                notWorkingTimeLogCount = operateHistoryMapper.getNotWorkingTimeLogCountByOrg(notWorkingTimeInitBo);
                redisUtils.set("operatorHistory:" + orgId,notWorkingTimeLogCount);
            }
        } else {
            notWorkingTimeLogCount = operateHistoryMapper.getNotWorkingTimeLogCountByOrg(notWorkingTimeInitBo);
        }
        //用户信息预警
        int integerBaseResult = operatorService.queryOperatorWarnCount();

        TerminaAuditCountDTO terminaAuditCountDTO = new TerminaAuditCountDTO();
        terminaAuditCountDTO.setTerminaAuditCount(terminaAuditCount);
        terminaAuditCountDTO.setLockAuditCount(lockAuditCount);
        terminaAuditCountDTO.setTailBoxCount(tailBoxCount);
        terminaAuditCountDTO.setKeyAuditCount(keyAuditCount);
        terminaAuditCountDTO.setPdaAuditCount(pdaAuditCount);
        terminaAuditCountDTO.setRfidAuditCount(rfidAuditCount);
        terminaAuditCountDTO.setNotWorkingTimeLogCount(notWorkingTimeLogCount);

        //任务种类统计 取前十
        List<TaskTypeDTO> taskTypeDTOList = taskMapper.getTaskTypes(orgIds);
        //辖区内设备种类统计 取前五
        List<RegionTerminalDTO> regionTerminalDTOList = terminalMapper.getRegionTerminalType(orgIds);
        //任务期限统计
        List<TaskTimeDTO> taskTimeDTOList = new ArrayList<>();
        //所有数据
        int allNum = taskMapper.getTaskTime(orgIds);
        //已生效数据
        int effectiveNum = taskMapper.getTaskCountByOrgId(orgIds);
        TaskTimeDTO effective = new TaskTimeDTO();
        effective.setState("1");
        effective.setCount(effectiveNum);
        taskTimeDTOList.add(effective);
        //已失效数据
        TaskTimeDTO expired = new TaskTimeDTO();
        expired.setState("2");
        expired.setCount(allNum - effectiveNum);
        taskTimeDTOList.add(expired);
        //三天内失效
        int result = taskMapper.getBeOverdueTask(orgIds);
        TaskTimeDTO taskTimeDTO = new TaskTimeDTO();
        taskTimeDTO.setState("3");
        taskTimeDTO.setCount(result);
        taskTimeDTOList.add(taskTimeDTO);

        homepageDisplayDTO.setNotUploadLogCount(notUploadLogCount);
        homepageDisplayDTO.setNotLockCount(notLockedCount);
  /*      homepageDisplayDTO.setLockOperatorCountBySameDay(lockOperatorCountBySameDay);
        homepageDisplayDTO.setLockOperatorCountBySameMonth(lockOperatorCountBySameMonth);
        homepageDisplayDTO.setTailBoxOperatorCountBySameDay(tailBoxOperatorCountBySameDay);
        homepageDisplayDTO.setTailBoxOperatorCountBySameMonth(tailBoxOperatorCountBySameMonth);*/
        homepageDisplayDTO.setOperatorAuditCount(operatorAuditCount);
        homepageDisplayDTO.setTaskAuditCount(taskAuditCount);
        homepageDisplayDTO.setTerminaAuditCountDTO(terminaAuditCountDTO);
        homepageDisplayDTO.setFingerprintAuditCount(fingerAuditCount);
        homepageDisplayDTO.setNotSignInCount(notSignInCount);
        homepageDisplayDTO.setOperatorWarn(integerBaseResult);

        homepageDisplayDTO.setTaskTypeDTOList(taskTypeDTOList);
        homepageDisplayDTO.setRegionTerminalDTOList(regionTerminalDTOList);
        homepageDisplayDTO.setTaskTimeDTOList(taskTimeDTOList);

        BaseResult<HomepageDisplayDTO> objectBaseResult = new BaseResult<>();
        objectBaseResult.setData(homepageDisplayDTO);
        objectBaseResult.setDataMessage("首页数据");
        objectBaseResult.setDataCode("00");
        return objectBaseResult;
    }

    @Override
    public List<MapDataDTO> getMapData(HttpServletRequest request) {
        List<MapDataDTO> list = new ArrayList<>();
        //获取所有省份编码
        List<String> proCodeList = cityMapper.getProCode();
        for (String proCode : proCodeList) {
            List<String> orgIds = organizationMapper.getOrgIdsByProCode(proCode);
            if (!orgIds.isEmpty()) {
                //获取机构下人员数量
                int operatorCount = operatorMapper.getOperatorCountByOrgId(orgIds);
                int terminalCount = terminalMapper.getTerminalCountByOrgId(orgIds);
                int taskCount = taskMapper.getTaskCountByOrgId(orgIds);
                MapDataDTO mapDataDTO = new MapDataDTO();
                mapDataDTO.setCode(proCode);
                mapDataDTO.setOperatorCount(operatorCount);
                mapDataDTO.setTerminalCount(terminalCount);
                mapDataDTO.setTaskCount(taskCount);
                list.add(mapDataDTO);
            }
        }
        return list;
    }

    @Override
    public List<MapDataDTO> getMapDataByProCode(MapDataBO mapDataBO, HttpServletRequest request) {
        List<MapDataDTO> list = new ArrayList<>();
        //获取当前省份下所有市的编码
        List<String> ctCodeList = cityMapper.getCtCode(mapDataBO.getProCode());
        for (String ctCode : ctCodeList) {
            List<String> orgIds = organizationMapper.getOrgIdsByCtCode(ctCode);
            if (!orgIds.isEmpty()) {
                //获取机构下人员数量
                int operatorCount = operatorMapper.getOperatorCountByOrgId(orgIds);
                int terminalCount = terminalMapper.getTerminalCountByOrgId(orgIds);
                int taskCount = taskMapper.getTaskCountByOrgId(orgIds);
                MapDataDTO mapDataDTO = new MapDataDTO();
                mapDataDTO.setCode(ctCode);
                mapDataDTO.setOperatorCount(operatorCount);
                mapDataDTO.setTerminalCount(terminalCount);
                mapDataDTO.setTaskCount(taskCount);
                list.add(mapDataDTO);
            }
        }
        return list;
    }

    @Override
    public List<MapDataDTO> getMapDataByCtCode(MapDataBO mapDataBO, HttpServletRequest request) {
        List<MapDataDTO> list = new ArrayList<>();
        //获取当前市下面所有的区/县的编码
        List<String> disCodeList = cityMapper.getCtCode(mapDataBO.getCtCode());
        for (String disCode : disCodeList) {
            List<String> orgIds = organizationMapper.getOrgIdsByDisCode(disCode);
            if (!orgIds.isEmpty()) {
                //获取机构下人员数量
                int operatorCount = operatorMapper.getOperatorCountByOrgId(orgIds);
                int terminalCount = terminalMapper.getTerminalCountByOrgId(orgIds);
                int taskCount = taskMapper.getTaskCountByOrgId(orgIds);
                MapDataDTO mapDataDTO = new MapDataDTO();
                mapDataDTO.setCode(disCode);
                mapDataDTO.setOperatorCount(operatorCount);
                mapDataDTO.setTerminalCount(terminalCount);
                mapDataDTO.setTaskCount(taskCount);
                list.add(mapDataDTO);
            }
        }
        return list;
    }

    @Override
    public List<String> getPopedomByOpId(HttpServletRequest request) {
        String opId = TokenUtil.getOpId(request.getHeader("token"));
        //获取当前登录用户角色
        String roleId = operatorMapper.getRoleIdByOpId(opId);
        //查询当前登录用户角色所拥有的权限 在指定的三个权限中筛选 020101 添加任务 030102 添加终端 030108 上传操作日志
        return popedomMapper.getPopedomIdByRoleId(roleId);
    }

    @Override
    public BaseResult<SignNumberResDTO> getUnSignNumber(HttpServletRequest request) {
        String orgId = TokenUtil.getOrgId(request.getHeader("token"));
        int number = terminalMapper.getUnSignNumber(orgId);
        SignNumberResDTO resDTO = new SignNumberResDTO();
        resDTO.setNumber(String.valueOf(number));
        return GetResult.getResult(resDTO);
    }

    public List<String> getListOrgIds(String orgId) {
        String strkey = "orgid:" + orgId;
        List<String> lists = null;
        lists = redisUtils.get(strkey, List.class);
        if (lists == null) {
            lists = new ArrayList<>();
            recursiveGetOrgId(lists, orgId);
            redisUtils.set(strkey, lists);
        }

        return lists;
    }


    //递归查询子机构
    private void recursiveGetOrgId(List<String> lists, String orgId) {
        List<String> orgIdList = organizationMapper.getOrgIdsList(orgId);
        while (orgIdList.isEmpty()) {
            return;
        }
        for (String childOrgId : orgIdList) {
            lists.add(childOrgId);
            recursiveGetOrgId(lists, childOrgId);
        }
    }
}
